package com.qk.management.web.filter;

import cn.hutool.core.util.ObjectUtil;
import com.qk.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;


import java.io.IOException;

/**
 * @Author:Shuna
 * @Date: 2025/10/11 10:59
 * @Description:
 */
//@WebFilter("/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    private static final String LOGIN_PATH = "/login";
    private static final String TOKEN_HEADER_NAME = "token";
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String path = req.getRequestURI();
        log.info("拦截到请求路径：{}", path);

        boolean isLoginReq = ObjectUtil.equals(path, LOGIN_PATH);
        if (isLoginReq) {
            chain.doFilter(request, response);
            return;
        }
        String token = req.getHeader(TOKEN_HEADER_NAME);
        if (ObjectUtil.isEmpty(token)){
            resp.setStatus(401);
            return;
        }
        try {
            Claims claims = JwtUtils.parseToken(token);
            chain.doFilter(req, resp);
            return;
        } catch (Exception e) {
            log.error("token解析失败：{}", e.getMessage());
            resp.setStatus(401);
        }

    }
}
